﻿
using System;
using EzDesk.Core.Model;
using EzDesk.DesktopClient.Model;
using EzDesk.DesktopClient.Event;
using EzDesk.DesktopClient.ServiceLocator.ClientTokenService;
using EzDesk.DesktopClient.ServiceLocator.CoreClientLoginService;
using EzDesk.EventAggregation;
using System.Runtime.InteropServices;
using System.Threading;
using EzDesk.Generic;

namespace EzDesk.DesktopClient
{
    public interface IUserManagement
    {
        string HeadIconUrl { get; }
        string UserToken { get; set; }
        UserProfile LogUser { get; }
        Dept LogUserDept { get; }
        UserState LogUserState { get; }
        void Login(string uid, string pwd);
        void Logout();
        string GetUrlWithUserToken(string url);
    }

    public class UserManagement : ManagementBase<UserManagement>, IUserManagement
    {
        private string _userToken;
        private DateTime _lastGetUserTokenDatetime = DateTime.MinValue;

        private const string HeadIconUrlBase = "/core/headicon";

        public string HeadIconUrl
        {
            get
            {
                if (!LogUserState.IsAvailable) return "";
                var iconString = "http://" + CoreClientService.GetClientBaseUrl() + HeadIconUrlBase + "/" +  CurrentUser.Id;
                return iconString;
            }
        }

        private string _currentTodoId = string.Empty;

        public string CurrentTodoId
        {
            get
            {
                //if (string.IsNullOrEmpty(_currentTodoId))
                //    _currentTodoId = CoreClientService.GetUserCurrentTodoItemId();
                return _currentTodoId;
            }
        }

        private IClientTokenService ClientTokenService
        {
            get { return ServiceLocator.ServiceFactory.TokenClientService; }
        }
        private ICoreClientLoginService CoreClientLoginService
        {
            get { return ServiceLocator.ServiceFactory.LoginService; }
        }

        public string UserToken
        {
            get
            {
                var dateTimeDiff = DateTime.Now - _lastGetUserTokenDatetime;
                if (dateTimeDiff.TotalMinutes > 20)
                    _userToken = ClientTokenService.RequestToken(this.LogUser.Id);

                return _userToken;
            }
            set
            {
                _userToken = value;
            }
        }

        public UserProfile LogUser
        {
            get;
            private set;
        }

        public Dept LogUserDept
        {
            get
            {
                if(LogUserState.IsAvailable)
                    return CoreClientService.GetDeptById(LogUser.DeptId.Value);
                return null;
            }
        }

        public UserState LogUserState
        {
            get;
            private set;
        }

        public UserManagement()
            : base()
        {
            InitProperty();
        }

        private void InitProperty()
        {
            LogUserState = new UserState();
        }

        public void Login(string uid, string pwd)
        {
            ThreadPool.QueueUserWorkItem(
                callback =>
                {
                    try
                    {
                        UserProfile userProfile = this.CoreClientLoginService.Login(uid, pwd);
                        if (userProfile == null)
                        {
                            LoginFaild("用户名或者密码错误","user");
                        }
                        else
                        {
                            InitUserInfo(userProfile);
                            PublishLoginSuccessMessage();
                        }
                    }
                    catch (Exception exp)
                    {
                        LogEx.ERROR("UserManagement",exp.Message,exp);
                        LoginFaild(exp.Message,"error");
                    }
                    
                });
        }

        public void Logout()
        {
            LogoutEvent.Instance.Publish(new LogoutArgs());
            SetCurrentUserDisable();
        }

        private void SetCurrentUserDisable()
        {
            LogUserState.IsAvailable = false;
        }


        private void InitUserInfo(UserProfile userProfile)
        {
            LogUser = userProfile;
            UserToken = ClientTokenService.RequestToken(userProfile.Id);
            LogUserState.IsAvailable = true;
        }

        private void PublishLoginSuccessMessage()
        {
            var args = new LoginArgs
            {
                IsSuccess = true,
                Message = "Success!"
            };
            LoginEvent.Instance.Publish(args);
            LoginedEvent.Instance.Publish(args);
        }

        private void LoginFaild(string information,string failedType)
        {
            LoginFailedEvent.Instance.Publish(new LoginFailedArgs(){ Information = information,  Type = failedType});
        }

        public string GetUrlWithUserToken(string url)
        {
            if (url.Contains("?"))
            {
                return url + "&" + UserTokenPairString;
            }
            else
            {
                return url + "?" + UserTokenPairString;
            }
        }

        private string UserTokenPairString
        {
            get
            {
                return "ez_auth_token=" + UserToken;
            }
        }
    }

}
